import React, { useEffect, useState } from 'react';
import { Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  CheckCircleTwoTone,
  CloseCircleTwoTone,
  LoadingOutlined,
  MinusCircleTwoTone,
} from '@ant-design/icons';
import { wsApi } from '@app-base/server';
import { useAsyncEffect } from 'ahooks';
import { ctx2 } from '@app-base/module';

interface DeviceData {
  key: string;
  name: string;
  status: 'success' | 'not_found' | 'installing' | 'pending';
  support: string;
}

const renderStatus = (status: DeviceData['status'], support: string) => {
  switch (status) {
    case 'success':
      return (
        <>
          <CheckCircleTwoTone
            twoToneColor='#52c41a'
            style={{ marginRight: 8 }}
          />
          {support}
        </>
      );
    case 'not_found':
      return (
        <>
          <CloseCircleTwoTone
            twoToneColor='#d9d9d9'
            style={{ marginRight: 8 }}
          />
          未找到匹配支架
        </>
      );
    case 'installing':
      return (
        <>
          <LoadingOutlined
            style={{ color: '#1890ff', marginRight: 8 }}
            spin
          />
          安装中
        </>
      );
    case 'pending':
      return (
        <>
          <MinusCircleTwoTone
            twoToneColor='#d9d9d9'
            style={{ marginRight: 8 }}
          />
          等待安装
        </>
      );
    default:
      return null;
  }
};

const columns: ColumnsType<DeviceData> = [
  {
    title: '设备编号',
    dataIndex: 'name',
    key: 'name',
    align: 'center',
  },
  {
    title: '支架信息',
    dataIndex: 'status',
    key: 'status',
    render: (_, record) => renderStatus(record.status, record.support),
  },
];

const AntdStatusTable: React.FC = () => {
  const [data, setData] = useState<DeviceData[]>([]);
  const [loading, setLoading] = useState(false);

  const handlePushConnection = (connection: any) => {
    if (connection.event === 'multiplepushes') {
      const data = connection.data || [];
      // 假设接口返回是一个数组
      if (Array.isArray(data)) {
        const mappedData: DeviceData[] = data.map(
          (item: any, index: number) => {
            // 状态映射
            let mappedStatus: DeviceData['status'] = 'pending';
            switch (item.status) {
              case 'success':
                mappedStatus = 'success';
                break;
              case 'fail':
                mappedStatus = 'not_found';
                break;
              case 'installing':
                mappedStatus = 'installing';
                break;
              case 'waiting':
                mappedStatus = 'pending';
                break;
            }

            return {
              key: index.toString(),
              name: item.clamp || `设备-${index + 1}`,
              support: item.bracket || '',
              status: mappedStatus,
            };
          },
        );

        setData(mappedData);
        setLoading(false);
      }
    }
  };
  useEffect(() => {
    ctx2.coreEngine.attach(handlePushConnection);
    return () => {
      ctx2.coreEngine.detach(handlePushConnection);
    };
  }, []);
  useAsyncEffect(async () => {
    try {
      await wsApi.execAiCmd({ c: 'InstallBrackets' });
    } catch (error) {
      setLoading(false);
    }
  }, []);

  return (
    <Table
      columns={columns}
      dataSource={data}
      pagination={false}
      bordered
      rowKey='key'
      loading={loading}
    />
  );
};

export default AntdStatusTable;
